﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data;

namespace SSCCMembership.Web.Services.Members
{
    [ErrorHandlerBehavior]
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UpdateDetailsComplete
    {

        const string Query =
            "SELECT        SSCC_DAT_Membership.ID, SSCC_DAT_Member.DoB, SSCC_DAT_Year.StartDate, SSCC_DAT_Membership.MembershipTypeRC, " +
            "              SSCC_DAT_Membership.BCUNumber, SSCC_DAT_Membership.BCURenewalDate, SSCC_DAT_Year.Year " +
            "FROM            SSCC_DAT_Member INNER JOIN " +
            "         SSCC_DAT_Membership ON SSCC_DAT_Member.ID = SSCC_DAT_Membership.Member INNER JOIN " +
            "         SSCC_DAT_Year ON SSCC_DAT_Membership.Year = SSCC_DAT_Year.ID " +
            "WHERE        (SSCC_DAT_Member.ID = @ID) AND (SSCC_DAT_Year.StartDate < @NOW) AND (SSCC_DAT_Year.EndDate > @NOW) ";

        [OperationContract]
        public void SaveComplete(int MemberID)
        {
            int MembershipID = 0;
            int? Age = null;
            int? MembershipTypeRC = null;
            string BCUNumber = "";
            DateTime? BCURenewalDate = null;
            int Year = 0;

            using (var Q = SSCCDatabase.Query(Query, new Dictionary<SqlParameter, object>(){
                {new SqlParameter("@ID", SqlDbType.Int), MemberID},
                {new SqlParameter("@NOW", SqlDbType.Date), DateTime.Now}
                }).First())
            {
                DateTime? DoBDate = Q["DoB"].Nullable<DateTime?>();
                DateTime? YearStartDate = Q["StartDate"].Nullable<DateTime?>();
                if (DoBDate.HasValue && YearStartDate.HasValue)
                {
                    //http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c/11942#11942
                    var CurrentDate = int.Parse(YearStartDate.Value.ToString("yyyyMMdd"));
                    var DOB = int.Parse(DoBDate.Value.ToString("yyyyMMdd"));
                    Age = (CurrentDate - DOB) / 10000;//Ignore Month and Day Properties.
                }
                MembershipTypeRC = Q["MembershipTypeRC"].Nullable<int?>();
                BCUNumber = Q["BCUNumber"].ToString();
                BCURenewalDate = Q["BCURenewalDate"].Nullable<DateTime?>();
                MembershipID = (int)Q["ID"];
                Year = (int)Q["Year"];
            }

            bool RequiresConcessionProof = false;
            if (MembershipTypeRC.HasValue)
            {
                using (var Q = SSCCDatabase.Query("SELECT RequiresConcessionProof FROM SSCC_DAT_MembershipType WHERE MembershipTypeRC=@MT AND Year=@Year",
                    new Params()
                    {
                        {new SqlParameter("@MT", SqlDbType.Int), MembershipTypeRC},
                        {new SqlParameter("@Year", SqlDbType.Int), Year}
                    }).First())
                {
                    RequiresConcessionProof = Q["RequiresConcessionProof"].Nullable<bool?>().HasValue && Q["RequiresConcessionProof"].Nullable<bool?>().Value;
                }
            }

            
            string Statement = "UPDATE SSCC_DAT_Membership SET "+
                "Age=@Age, "+
                "ParentalConsentReqd=@ParentConsent, "+
                "RenewChecked='True', "+
              //  "BCUCardReqd=@BCUCardReqd, " +
                "SignatureReqd='True', "+
                "ConcessionProofReqd= @Concession " +
                "WHERE ID=@ID";
            var Parameters = new Params()
            {
                {new SqlParameter("@ID", SqlDbType.Int), MembershipID},
                {new SqlParameter("@Age", SqlDbType.Int), Age.ToDBNullable()},
                {new SqlParameter("@ParentConsent", SqlDbType.Bit), (Age.HasValue)&&(Age.Value < 18)},
              //BCUCard Reqd now maintained by user directly as BCU member field in the memberships section of the page 
              //{new SqlParameter("@BCUCardReqd", SqlDbType.Bit), (MembershipTypeRC.GetRefCodeMetadata<bool>() && BCUNumber.Length != 0 && BCURenewalDate.HasValue && BCURenewalDate.Value > DateTime.Now)},
                {new SqlParameter("@Concession", SqlDbType.Bit), RequiresConcessionProof}
            };
            SSCCDatabase.ExecuteStatement(Statement, Parameters);

            SSCCDatabase.ExecuteStatement("UPDATE SSCC_DAT_RackAllocation SET Renew=1 WHERE Membership=@MID",
                new SqlParameter("@MID", SqlDbType.Int), MembershipID);
        }

        // Add more operations here and mark them with [OperationContract]
    }
}
